package team.szm.scd.controller;

import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import team.szm.scd.database.dto.Result;
import team.szm.scd.database.dto.VerifyCode;
import team.szm.scd.utils.EncodeUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@Slf4j
public class VerifyCodeController {
    @Resource
    Producer producer;

    @RequestMapping("/verify_code")
    public Result<VerifyCode> getVerifyCode(HttpSession session) {
        String code = producer.createText();
        session.setAttribute("verify_code", code);
        BufferedImage image = producer.createImage(code);
        String img_base64;
        try {
            img_base64 = EncodeUtils.GetBase64FromImage(image);
        } catch (IOException e) {
            log.error(e.toString());
            return Result.fail("验证码生成错误", new VerifyCode(null));
        }
        return Result.success(new VerifyCode(img_base64));
    }
}
